<!DOCTYPE html><html lang="zh-Hans"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="iOS多线程"><meta name="keywords" content=""><meta name="author" content="kyren"><meta name="copyright" content="kyren"><title>iOS多线程 | Kyren's Blog</title><link rel="shortcut icon" href="/melody-favicon.ico"><link rel="stylesheet" href="/css/index.css?version=1.9.0"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.9.0"><meta name="format-detection" content="telephone=no"><meta http-equiv="x-dns-prefetch-control" content="on"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="dns-prefetch" href="https://hm.baidu.com"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?cf87fcdbd9ab7cf93d894f7c219ae78f";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();</script><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><script src="https://v1.hitokoto.cn/?encode=js&amp;charset=utf-8&amp;select=.footer_custom_text" defer></script><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容:${query}"}},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  hexoVersion: '6.2.0'
} </script><meta name="generator" content="Hexo 6.2.0"></head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar" data-display="true"><div class="toggle-sidebar-info text-center"><span data-toggle="切换文章详情">切换站点概览</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">目录</div><div class="sidebar-toc__progress"><span class="progress-notice">你已经读了</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E6%A6%82%E5%BF%B5"><span class="toc-number">1.</span> <span class="toc-text">基本概念</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%80%E3%80%81NSThread"><span class="toc-number">2.</span> <span class="toc-text">一、NSThread</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BA%8C%E3%80%81GCD-%E8%8B%B1%E6%96%87%E5%85%A8%E7%A7%B0-Grand-Central-Dispatch"><span class="toc-number">3.</span> <span class="toc-text">二、GCD(英文全称:Grand Central Dispatch)</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E9%98%9F%E5%88%97"><span class="toc-number"></span> <span class="toc-text">创建队列</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#1%E3%80%81%E4%B8%BB%E9%98%9F%E5%88%97-%E4%B8%B2%E8%A1%8C%E9%98%9F%E5%88%97"><span class="toc-number">0.1.</span> <span class="toc-text">1、主队列(串行队列)</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2%E3%80%81%E5%85%A8%E5%B1%80%E5%B9%B6%E8%A1%8C%E9%98%9F%E5%88%97"><span class="toc-number">0.2.</span> <span class="toc-text">2、全局并行队列</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#3%E3%80%81%E8%87%AA%E5%AE%9A%E4%B9%89%E9%98%9F%E5%88%97"><span class="toc-number">0.3.</span> <span class="toc-text">3、自定义队列</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E4%BB%BB%E5%8A%A1"><span class="toc-number"></span> <span class="toc-text">创建任务</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#NSOperation"><span class="toc-number">1.</span> <span class="toc-text">NSOperation</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#NSOperationQueue"><span class="toc-number">1.1.</span> <span class="toc-text">NSOperationQueue</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%A4%E7%A7%8D%E9%98%9F%E5%88%97-NSOperation"><span class="toc-number"></span> <span class="toc-text">两种队列(NSOperation)</span></a></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="https://avatars.githubusercontent.com/u/5827823?v=4"></div><div class="author-info__name text-center">kyren</div><div class="author-info__description text-center">huluo的技术博客</div><div class="follow-button"><a target="_blank" rel="noopener" href="https://github.com/huluo666">Follow Me</a></div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">文章</span><span class="pull-right">239</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">标签</span><span class="pull-right">41</span></a><a class="author-info-articles__categories article-meta" href="/categories"><span class="pull-left">分类</span><span class="pull-right">29</span></a></div><hr><div class="author-info-links"><div class="author-info-links__title text-center">Links</div><a class="author-info-links__name text-center" target="_blank" rel="noopener" href="http://192.168.2.212:9090/">Jira</a><a class="author-info-links__name text-center" target="_blank" rel="noopener" href="http://192.168.2.212:8090/">Confluence</a><a class="author-info-links__name text-center" target="_blank" rel="noopener" href="http://bloc.leniugame.com/">Leniu</a></div></div></div><div id="content-outer"><div class="no-bg" id="top-container"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">Kyren's Blog</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus">   <a class="site-page" href="/">主页</a><a class="site-page" href="/essay">随笔</a><a class="site-page" href="/archives">归档</a><a class="site-page" href="/tags">标签</a><a class="site-page" href="/categories">分类</a><a class="site-page" href="/about">关于</a></span><span class="pull-right"><a class="site-page social-icon search"><i class="fa fa-search"></i><span> 搜索</span></a></span></div><div id="post-info"><div id="post-title">iOS多线程</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2018-03-26</time></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><p>在 iOS 中其实目前有 <code>4</code> 套多线程方案</p>
<ul>
<li>NSThread</li>
<li>GCD</li>
<li>NSOperation &amp; NSOperationQueue</li>
<li>Pthreads(基于<strong>c语言</strong>的框架,不常用)</li>
</ul>
<h4 id="基本概念"><a href="#基本概念" class="headerlink" title="基本概念"></a>基本概念</h4><table>
<thead>
<tr>
<th>名称</th>
<th>概念</th>
</tr>
</thead>
<tbody><tr>
<td>进程</td>
<td>一个具有一定独立功能的程序关于某个数据集合的一次运行活动。可以理解成一个运行中的应用程序</td>
</tr>
<tr>
<td>线程</td>
<td>程序执行流的最小单元，线程是进程中的一个实体。</td>
</tr>
<tr>
<td>同步</td>
<td>只能在当前线程按先后顺序依次执行，不开启新线程。</td>
</tr>
<tr>
<td>异步</td>
<td>可以在当前线程开启多个新线程执行，可不按顺序执行。  队列： 装载线程任务的队形结构。  并发： 线程执行可以同时一起进行执行。  串行： 线程执行只能依次逐一先后有序的执行。</td>
</tr>
<tr>
<td>队列</td>
<td>装载线程任务的队形结构。  并发： 线程执行可以同时一起进行执行。  串行： 线程执行只能依次逐一先后有序的执行。</td>
</tr>
<tr>
<td>并发</td>
<td>线程执行可以同时一起进行执行。</td>
</tr>
<tr>
<td>串行</td>
<td>线程执行只能依次逐一先后有序的执行。</td>
</tr>
</tbody></table>
<blockquote>
<p>备注：一个进程可有多个线程-&gt;一个进程可有多个队列-&gt;队列可分并发队列和串行队列。</p>
</blockquote>
<h4 id="一、NSThread"><a href="#一、NSThread" class="headerlink" title="一、NSThread"></a>一、NSThread</h4><p>这套方案是经过苹果封装后的，并且完全面向对象的。</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 方法一：创建线程，需要自己开启线程</span></span><br><span class="line"><span class="built_in">NSThread</span> *thread = [[<span class="built_in">NSThread</span> alloc]initWithTarget:<span class="keyword">self</span> selector:<span class="keyword">@selector</span>(run) object:<span class="literal">nil</span>];</span><br><span class="line">thread.threadPriority = <span class="number">1</span>;<span class="comment">// 设置线程的优先级(0.0 - 1.0，1.0最高级)</span></span><br><span class="line"><span class="comment">// 开启线程</span></span><br><span class="line">[thread start];</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法二：静态实例化-创建线程后自动启动线程</span></span><br><span class="line">[<span class="built_in">NSThread</span> detachNewThreadSelector:<span class="keyword">@selector</span>(run) toTarget:<span class="keyword">self</span> withObject:<span class="literal">nil</span>];</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法三：隐式实例化-隐式创建并启动线程</span></span><br><span class="line">[<span class="keyword">self</span> performSelectorInBackground:<span class="keyword">@selector</span>(run) withObject:<span class="literal">nil</span>];</span><br></pre></td></tr></table></figure>



<h4 id="二、GCD-英文全称-Grand-Central-Dispatch"><a href="#二、GCD-英文全称-Grand-Central-Dispatch" class="headerlink" title="二、GCD(英文全称:Grand Central Dispatch)"></a>二、GCD(英文全称:Grand Central Dispatch)</h4><ul>
<li>GCD是苹果开发的一个多核编程的解决方法</li>
<li>GCD是苹果推荐而且最简洁的;</li>
<li>纯C语言，提供了非常多强大的函数；</li>
<li>GCD会自动利用更多的CPU内核（比如双核、四核);</li>
<li>GCD会自动管理线程的生命周期（创建线程、调度任务、销毁线程）;</li>
</ul>
<p>GCD是基于C的API，因此比较底层。</p>
<p>GCD所管理的调度队列（dispatch queue）主要有三类，1、<strong>串行队列</strong>（private dispatch queue）、2、<strong>并发队列</strong> （global dispatch queue，又称全局调度队列）和<strong>主队列</strong>（main dispatch queue）。</p>
<p><strong>队列与任务</strong></p>
<p>GCD有四个概念：串行队列、并行队列、同步、异步四者。</p>
<p><code>同步（sync）</code> 和 <code>异步（async）</code> 的主要区别在于会不会阻塞当前线程，直到 <code>Block</code> 中的任务执行完毕！</p>
<p><strong>同步(sync)</strong> ：它会阻塞当前线程并等待 <code>Block</code> 中的任务执行完毕，然后当前线程才会继续往下运行。</p>
<p>**异步(async)**：当前线程会直接往下执行，它不会阻塞当前线程。</p>
<p><strong>队列</strong>：用于存放任务。一共有两种队列， <strong>串行队列</strong> 和 <strong>并行队列</strong>。</p>
<p>队列**：用于存放任务。一共有两种队列， <strong>串行队列</strong> 和 <strong>并行队列</strong>。</p>
<table>
<thead>
<tr>
<th>名称</th>
<th>简介</th>
</tr>
</thead>
<tbody><tr>
<td>同步</td>
<td>完成需要做的任务后才会返回，进行下一任务(“任务”，在 GCD 里指的是 Block；在 performSelector 方法中，对应 selector 方法。同步方法，功能类似 <code>dispatch_group_wait</code> ，而 group 指的是所有线程，包括主线程。)</td>
</tr>
<tr>
<td>异步</td>
<td>不会等待任务完成才返回，会立即返回。(异步是多线程的代名词，因为必定会开启新的线程，线程的申请是由异步负责，起到开分支的作用。)</td>
</tr>
<tr>
<td>串行队列</td>
<td>任务依次执行(同一时间队列中只有一个任务在执行，每个任务只有在前一个任务执行完成后才能开始执行。)</td>
</tr>
<tr>
<td>并行队列</td>
<td>任务并发执行(你唯一能保证的是，这些任务会按照被添加的顺序开始执行。但是任务可以以任何顺序完成)</td>
</tr>
<tr>
<td>全局队列</td>
<td>隶属于并行队列,不要与 barrier 栅栏方法搭配使用， barrier 只有与自定义的并行队列一起使用，才能让 barrier 达到我们所期望的栅栏功能。与 串行队列或者 global 队列 一起使用，barrier 的表现会和 dispatch_sync 方法一样。</td>
</tr>
<tr>
<td>主队列</td>
<td>隶属于串行队列,不能与 sync 同步方法搭配使用，会造成死循环（ 主队列是GCD自带的一种特殊的串行队列，放在主队列中的任务，都会放到主线程中执行）</td>
</tr>
</tbody></table>
<p><strong>自定义队列</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Serial Dispatch Queue:串行调度队列</span><br><span class="line">Concurrent Dispatch Queue:并发调度队列</span><br><span class="line">Serial:串行 Concurrent:同时   并发:Concurrency  并行:Parallelism</span><br></pre></td></tr></table></figure>

<p>并发和并行都是指多个任务可以同时执行，都属于多线程编程概念，因此二者必然十分相近，容易混淆。二者区别只有一点，即是否多任务执行于严格的同一时刻。并发不是，并行是。</p>
<table>
<thead>
<tr>
<th>说明</th>
<th>Dispatch Queue分类</th>
</tr>
</thead>
<tbody><tr>
<td>串行的队列，每次只能执行一个任务，并且必须等待前一个执行任务完成</td>
<td>Serial Dispatch Queue</td>
</tr>
<tr>
<td>一次可以并发执行多个任务，不必等待执行中的任务完成</td>
<td>Concurrent Dispatch Queue</td>
</tr>
</tbody></table>
<table>
<thead>
<tr>
<th></th>
<th>同步执行</th>
<th>异步执行</th>
</tr>
</thead>
<tbody><tr>
<td>串行队列</td>
<td>当前线程，一个一个执行( 不会新建线程)</td>
<td>其他线程，一个一个执行, 每次使用 createDispatch 方法就会新建一条线程, 多条线程间会并行执行</td>
</tr>
<tr>
<td>并发队列</td>
<td>当前线程，一个一个执行( 不会新建线程)</td>
<td>开很多线程，一起执行( iOS7-SDK 时代一般是5、6条， iOS8-SDK 以后可以50、60条)</td>
</tr>
</tbody></table>
<p><a target="_blank" rel="noopener" href="https://www.zhihu.com/question/33515481">并发与并行的区别？</a></p>
<p>GCD使用步骤：</p>
<ol>
<li>定制任务<br>确定想做的事情，在 GCD 里指的是 Block</li>
<li>将任务添加到队列中<br>GCD会自动将队列中的任务取出，放到对应的线程中执行<br>任务的取出遵循队列的FIFO原则：先进先出，后进后出</li>
</ol>
<h3 id="创建队列"><a href="#创建队列" class="headerlink" title="创建队列"></a>创建队列</h3><p>iOS 中, 队列主要分为:</p>
<ul>
<li><p>全局队列(dispatch_get_main_queue)</p>
</li>
<li><p>主队列(dispatch_get_global_queue)</p>
</li>
<li><p>自定义队列(dispatch_queue_create)</p>
<p>①串行队列(dispatch_queue_create-DISPATCH_QUEUE_SERIAL)</p>
<p>②并发队列(dispatch_queue_create-DISPATCH_QUEUE_CONCURRENT)</p>
</li>
</ul>
<h5 id="1、主队列-串行队列"><a href="#1、主队列-串行队列" class="headerlink" title="1、主队列(串行队列)"></a>1、主队列(串行队列)</h5><p>它用于刷新 UI，任何需要刷新 UI 的工作都要在主队列执行，所以一般耗时的任务都要放到别的线程执行。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">dispatch_queue_t queue = dispatch_get_main_queue;</span><br></pre></td></tr></table></figure>

<h5 id="2、全局并行队列"><a href="#2、全局并行队列" class="headerlink" title="2、全局并行队列"></a>2、全局并行队列</h5><p>只要是并行任务一般都加入到这个队列。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);</span><br></pre></td></tr></table></figure>

<h5 id="3、自定义队列"><a href="#3、自定义队列" class="headerlink" title="3、自定义队列"></a>3、自定义队列</h5><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">//串行队列</span><br><span class="line">dispatch_queue_t queue = dispatch_queue_create(&quot;com.gcd.serialQueue&quot;, NULL);</span><br><span class="line">dispatch_queue_t queue = dispatch_queue_create(&quot;com.gcd.serialQueue&quot;, DISPATCH_QUEUE_SERIAL);</span><br><span class="line"></span><br><span class="line">//并发(行)队列</span><br><span class="line">dispatch_queue_t queue = dispatch_queue_create(&quot;com.gcd.conQueue&quot;, DISPATCH_QUEUE_CONCURRENT);</span><br></pre></td></tr></table></figure>

<h3 id="创建任务"><a href="#创建任务" class="headerlink" title="创建任务"></a>创建任务</h3><ul>
<li>分为同步任务和异步任务</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">//串行</span><br><span class="line">dispatch_queue_t queue = dispatch_queue_create(&quot;serial_queue&quot;, DISPATCH_QUEUE_SERIAL);</span><br><span class="line">//并发</span><br><span class="line">dispatch_queue_t queue = dispatch_queue_create(&quot;serial_queue&quot;, DISPATCH_QUEUE_CONCURRENT);</span><br><span class="line"></span><br><span class="line">//同步</span><br><span class="line">dispatch_sync(queue, ^&#123;</span><br><span class="line">  NSLog(@&quot;%@&quot;, [NSThread currentThread]);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">//异步</span><br><span class="line">dispatch_async(queue, ^&#123;</span><br><span class="line">   NSLog(@&quot;%@&quot;, [NSThread currentThread]);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>



<h4 id="NSOperation"><a href="#NSOperation" class="headerlink" title="NSOperation"></a>NSOperation</h4><p>NSOperation 是苹果公司对 GCD 的封装，完全面向对象，<code>NSOperation</code> 和 <code>NSOperationQueue</code> 分别对应 GCD 的任务和队列 。操作步骤也很好理解：</p>
<ul>
<li><p>①将要执行的任务封装到一个 NSOperation 对象中。</p>
</li>
<li><p>②将此任务添加到一个 NSOperationQueue 对象中。</p>
</li>
</ul>
<p>NSOperation 只是一个抽象类，所以不能封装任务。但它有 2 个子类用于封装任务。分别是：<code>NSInvocationOperation</code> 和 <code>NSBlockOperation</code> 。创建一个 Operation 后，需要调用 start 方法来启动任务，它会 默认在当前队列同步执行。当然你也可以在中途取消一个任务，只需要调用其 <code>cancel</code>方法即可。</p>
<figure class="highlight plaintext"><figcaption><span>c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">//1.创建NSInvocationOperation对象</span><br><span class="line">NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run) object:nil];</span><br><span class="line"></span><br><span class="line">//2.开始执行</span><br><span class="line">[operation start];</span><br><span class="line"></span><br><span class="line">//1.创建NSBlockOperation对象</span><br><span class="line">NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^&#123;</span><br><span class="line">    NSLog(@&quot;%@&quot;, [NSThread currentThread]);</span><br><span class="line">&#125;];</span><br><span class="line"></span><br><span class="line">//2.开始任务</span><br><span class="line">[operation start];</span><br></pre></td></tr></table></figure>

<h5 id="NSOperationQueue"><a href="#NSOperationQueue" class="headerlink" title="NSOperationQueue"></a>NSOperationQueue</h5><p>NSOperationQueue是对GCD的objectivec封装，相对于GCD具有更多先进的特性，如可以添加NSOperation依赖，取消NSOperation等。</p>
<p>NSOperationQueue是并发队列，且不遵循先进先出FIFO排序原则。</p>
<h3 id="两种队列-NSOperation"><a href="#两种队列-NSOperation" class="headerlink" title="两种队列(NSOperation)"></a>两种队列(NSOperation)</h3><p>NSOperationQueue 有两种不同类型的队列：主队列和自定义队列。主队列运行在主线程之上，而自定义队列在后台执行。在两种类型中，这些队列所处理的任务都使用 NSOperation 的子类来表述。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];  //主队列</span><br><span class="line">NSOperationQueue *queue = [[NSOperationQueue alloc] init]; //自定义队列</span><br><span class="line"></span><br><span class="line">//添加一个NSOperation</span><br><span class="line">[queue addOperation:operation]</span><br><span class="line"></span><br><span class="line">//添加一组NSOperation</span><br><span class="line">[queue addOperations:operations waitUntilFinished:NO</span><br><span class="line"></span><br><span class="line">//添加一个block形式的Operation</span><br><span class="line">[queue addOperationWithBlock:^&#123;</span><br><span class="line">    //执行一个Block的操作</span><br><span class="line">&#125;];</span><br><span class="line"></span><br><span class="line">[queue setMaxConcurrentOperationCount:1];</span><br><span class="line"></span><br><span class="line">//单个NSOperation取消</span><br><span class="line">[operation cancel]</span><br><span class="line"></span><br><span class="line">//取消NSOperationQueue中的所有操作</span><br><span class="line">[queue cancelAllOperations]</span><br><span class="line"></span><br><span class="line">// 暂停queue</span><br><span class="line">[queue setSuspended:YES];</span><br></pre></td></tr></table></figure>

<p>NSOperation 有一个非常实用的功能，那就是添加依赖。比如有 3 个任务：A: 从服务器上下载一张图片，B：给这张图片加个水印，C：把图片返回给服务器。这时就可以用到依赖了:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">//1.任务一：下载图片</span><br><span class="line">NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^&#123;</span><br><span class="line">    NSLog(@&quot;下载图片 - %@&quot;, [NSThread currentThread]);</span><br><span class="line">    [NSThread sleepForTimeInterval:1.0];</span><br><span class="line">&#125;];</span><br><span class="line"></span><br><span class="line">//2.任务二：打水印</span><br><span class="line">NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^&#123;</span><br><span class="line">    NSLog(@&quot;打水印   - %@&quot;, [NSThread currentThread]);</span><br><span class="line">    [NSThread sleepForTimeInterval:1.0];</span><br><span class="line">&#125;];</span><br><span class="line"></span><br><span class="line">//3.任务三：上传图片</span><br><span class="line">NSBlockOperation *operation3 = [NSBlockOperation blockOperationWithBlock:^&#123;</span><br><span class="line">    NSLog(@&quot;上传图片 - %@&quot;, [NSThread currentThread]);</span><br><span class="line">    [NSThread sleepForTimeInterval:1.0];</span><br><span class="line">&#125;];</span><br><span class="line"></span><br><span class="line">//4.设置依赖</span><br><span class="line">[operation2 addDependency:operation1];      //任务二依赖任务一</span><br><span class="line">[operation3 addDependency:operation2];      //任务三依赖任务二</span><br><span class="line"></span><br><span class="line">//5.创建队列并加入任务</span><br><span class="line">NSOperationQueue *queue = [[NSOperationQueue alloc] init];</span><br><span class="line">[queue addOperations:@[operation3, operation2, operation1] waitUntilFinished:NO];</span><br></pre></td></tr></table></figure>





<p><a target="_blank" rel="noopener" href="http://jumpingfrog0.github.io/2017/2017-04-20-iOS%E5%A4%9A%E7%BA%BF%E7%A8%8B%E6%80%BB%E7%BB%93/">http://jumpingfrog0.github.io/2017/2017-04-20-iOS%E5%A4%9A%E7%BA%BF%E7%A8%8B%E6%80%BB%E7%BB%93/</a></p>
<p><a target="_blank" rel="noopener" href="https://blog.cnbluebox.com/blog/2014/07/01/cocoashen-ru-xue-xi-nsoperationqueuehe-nsoperationyuan-li-he-shi-yong/">https://blog.cnbluebox.com/blog/2014/07/01/cocoashen-ru-xue-xi-nsoperationqueuehe-nsoperationyuan-li-he-shi-yong/</a></p>
<p><a target="_blank" rel="noopener" href="http://www.cnblogs.com/kenshincui/p/3983982.html">iOS开发系列–并行开发其实很容易</a></p>
</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">kyren</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://huluo666.gitee.io/2018/03/26/iOS多线程/">http://huluo666.gitee.io/2018/03/26/iOS多线程/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://huluo666.gitee.io">Kyren's Blog</a>！</span></div></div><div class="post-meta__tag-list"></div><nav id="pagination"><div class="prev-post pull-left"><a href="/2018/03/27/iOS%E5%B8%B8%E7%94%A8%E7%AC%AC%E4%B8%89%E5%88%86%E5%BA%93%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/"><i class="fa fa-chevron-left">  </i><span>iOS常用第三分库源码分析</span></a></div><div class="next-post pull-right"><a href="/2018/03/23/iOS%E4%B8%ADClass%E7%9B%B8%E5%85%B3%E6%96%B9%E6%B3%95%E5%8C%BA%E5%88%AB/"><span>iOS中Class相关方法区别</span><i class="fa fa-chevron-right"></i></a></div></nav></div></div><footer><div class="layout" id="footer"><div class="copyright">&copy;2022 By kyren</div><div class="framework-info"><span>驱动 - </span><a target="_blank" rel="noopener" href="http://hexo.io"><span>Hexo</span></a><span class="footer-separator">|</span><span>主题 - </span><a target="_blank" rel="noopener" href="https://github.com/Molunerfinn/hexo-theme-melody"><span>Melody</span></a></div><div class="footer_custom_text">hitokoto</div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv"><i class="fa fa-file"></i><span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/lib/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.9.0"></script><script src="/js/fancybox.js?version=1.9.0"></script><script src="/js/sidebar.js?version=1.9.0"></script><script src="/js/copy.js?version=1.9.0"></script><script src="/js/fireworks.js?version=1.9.0"></script><script src="/js/transition.js?version=1.9.0"></script><script src="/js/scroll.js?version=1.9.0"></script><script src="/js/head.js?version=1.9.0"></script><script src="/js/search/local-search.js"></script><script>if(/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
  $('#top-container').addClass('is-mobile')
}</script><div class="search-dialog" id="local-search"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章"></div></div></div><hr><div id="local-search-results"><div id="local-hits"></div><div id="local-stats"><div class="local-search-stats__hr" id="hr"><span>由</span> <a target="_blank" rel="noopener" href="https://github.com/wzpan/hexo-generator-search" style="color:#49B1F5;">hexo-generator-search</a>
 <span>提供支持</span></div></div></div><span class="search-close-button"><i class="fa fa-times"></i></span></div><div class="search-mask"></div></body></html>